using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UniversalAdmin.Api.Models;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Features.Menus.Commands.CreateMenu;
using UniversalAdmin.Application.Features.Menus.Commands.DeleteMenu;
using UniversalAdmin.Application.Features.Menus.Commands.ReorderMenu;
using UniversalAdmin.Application.Features.Menus.Commands.UpdateMenu;
using UniversalAdmin.Application.Features.Menus.Queries.GetFlatMenus;
using UniversalAdmin.Application.Features.Menus.Queries.GetMenuTree;
using UniversalAdmin.Application.Features.Menus.Queries.GetPagedMenus;
using UniversalAdmin.Application.Features.Menus.Queries.SearchMenus;

namespace UniversalAdmin.Api.Controllers;

/// <summary>
/// 菜单管理控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class MenusController : ControllerBase
{
  private readonly IMediator _mediator;

  public MenusController(IMediator mediator)
  {
    _mediator = mediator;
  }

  /// <summary>
  /// 获取菜单树结构
  /// </summary>
  /// <returns>菜单树列表</returns>
  [HttpGet("tree")]
  [Authorize("menu.view")]
  public async Task<IActionResult> GetMenuTree()
  {
    var result = await _mediator.Send(new GetMenuTreeQuery());
    return Ok(ApiResponse<List<MenuTreeDto>>.Success(result.Data!, "获取菜单树成功"));
  }

  /// <summary>
  /// 获取菜单列表（分页）
  /// </summary>
  /// <param name="page">页码</param>
  /// <param name="size">每页数量</param>
  /// <param name="keyword">搜索关键词</param>
  /// <param name="isActive">是否激活</param>
  /// <param name="parentId">父级菜单ID</param>
  /// <returns>分页菜单列表</returns>
  [HttpGet]
  [Authorize("menu.view")]
  public async Task<IActionResult> GetMenus(
      [FromQuery] int page = 1,
      [FromQuery] int size = 10,
      [FromQuery] string? keyword = null,
      [FromQuery] bool? isActive = null,
      [FromQuery] int? parentId = null)
  {
    var result = await _mediator.Send(new GetPagedMenusQuery(
        page, size, keyword, isActive, parentId));

    if (!result.Ok)
      return BadRequest(ApiResponse.Error(result.Code, result.Message));

    return Ok(ApiResponse<PagedResult<MenuFlatDto>>.Success(result.Data!, "获取菜单列表成功"));
  }

  /// <summary>
  /// 获取菜单详情
  /// </summary>
  /// <param name="id">菜单ID</param>
  /// <returns>菜单详情</returns>
  [HttpGet("{id:int}")]
  [Authorize("menu.view")]
  public async Task<IActionResult> GetMenu(int id)
  {
    // 这里需要实现获取单个菜单详情的Query和Handler
    // 临时使用扁平菜单列表
    var result = await _mediator.Send(new GetFlatMenusQuery());
    var menu = result.Data?.FirstOrDefault(m => m.Id == id);

    if (menu == null)
      return NotFound(ApiResponse.Error(404, "菜单不存在"));

    return Ok(ApiResponse<MenuFlatDto>.Success(menu, "获取菜单详情成功"));
  }

  [HttpGet("search")]
  [Authorize("menu.view")]
  public async Task<IActionResult> SearchMenus(
      [FromQuery] string? keyword = null,
      [FromQuery] bool? isActive = null,
      [FromQuery] int page = 1,
      [FromQuery] int size = 10)
  {
    var result = await _mediator.Send(new SearchMenusQuery(keyword, isActive, page, size));
    return Ok(ApiResponse<PagedResult<MenuDto>>.Success(result.Data!, "查询成功"));
  }

  /// <summary>
  /// 创建菜单
  /// </summary>
  /// <param name="request">创建菜单请求</param>
  /// <returns>创建后的菜单信息</returns>
  [HttpPost]
  [Authorize("menu.create")]
  public async Task<IActionResult> CreateMenu([FromBody] CreateMenuDto request)
  {
    if (!ModelState.IsValid)
      return BadRequest(ApiResponse.Error(400, "请求参数错误", ModelState));

    var result = await _mediator.Send(new CreateMenuCommand(request));

    if (!result.Ok)
      return BadRequest(ApiResponse.Error(result.Code, result.Message));

    return Ok(ApiResponse<MenuFlatDto>.Success(result.Data!, "菜单创建成功"));
  }

  /// <summary>
  /// 更新菜单
  /// </summary>
  /// <param name="id">菜单ID</param>
  /// <param name="request">更新菜单请求</param>
  /// <returns>更新后的菜单信息</returns>
  [HttpPut("{id:int}")]
  [Authorize("menu.update")]
  public async Task<IActionResult> UpdateMenu(int id, [FromBody] UpdateMenuDto request)
  {
    if (!ModelState.IsValid)
      return BadRequest(ApiResponse.Error(400, "请求参数错误", ModelState));

    var result = await _mediator.Send(new UpdateMenuCommand(id, request));

    if (!result.Ok)
      return BadRequest(ApiResponse.Error(result.Code, result.Message));

    return Ok(ApiResponse<MenuFlatDto>.Success(result.Data!, "菜单更新成功"));
  }

  /// <summary>
  /// 删除菜单
  /// </summary>
  /// <param name="id">菜单ID</param>
  /// <returns>删除结果</returns>
  [HttpDelete("{id:int}")]
  [Authorize("menu.delete")]
  public async Task<IActionResult> DeleteMenu(int id)
  {
    var result = await _mediator.Send(new DeleteMenuCommand(id));

    if (!result.Ok)
      return BadRequest(ApiResponse.Error(result.Code, result.Message));

    return Ok(ApiResponse.Success("菜单删除成功"));
  }

  /// <summary>
  /// 更新菜单排序
  /// </summary>
  /// <param name="request">排序请求</param>
  /// <returns>排序结果</returns>
  [HttpPut("sort")]
  [Authorize("menu.update")]
  public async Task<IActionResult> ReorderMenu([FromBody] ReorderMenuRequest request)
  {
    if (!ModelState.IsValid)
      return BadRequest(ApiResponse.Error(400, "请求参数错误", ModelState));

    // 这里需要根据dragId和dropId计算出新的排序
    // 临时实现：假设已经计算好排序
    var result = await _mediator.Send(new ReorderMenuCommand(
        request.ParentId ?? 0,
        request.OrderedIds ?? new List<int>()));

    if (!result.Ok)
      return BadRequest(ApiResponse.Error(result.Code, result.Message));

    return Ok(ApiResponse.Success("菜单排序更新成功"));
  }
}

/// <summary>
/// 菜单排序请求模型
/// </summary>
public class ReorderMenuRequest
{
  public int? ParentId { get; set; }
  public List<int>? OrderedIds { get; set; }
}